package pers.bc.utils.yonyou;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;

import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.RuntimeEnv;
import nc.bs.logging.Logger;
import nc.secutity.toolkit.SignatureTookKit;
import pers.bc.utils.pub.CollectionUtil;
import pers.bc.utils.pub.JudgeAssertUtil;
import pers.bc.utils.pub.LoggerUtil;
import pers.bc.utils.pub.PropertiesUtil;
import pers.bc.utils.pub.PubEnvUtil;
import pers.bc.utils.pub.StringUtil;

/**
 * yonbip高级版单点登录
 * ThirdPartyLoginVerfiy这个类，是验证用户的 <br>
 * 单点登录用的uase_code_q 字段<br>
 * @see https://community.yonyou.com/ifr/c/y?service=https%3A%2F%2Fc2.yonyoucloud.com%2Fiuap-hc-client%2Fucf-wh%2Fclient%2Findex.html%23%2Fdetail%2FGJDDDL1%3FnodeId%3De9c26a4c-af37-43fa-b1b4-d3a6d3acf9dc%26productline%3DCommunityDoc%26headerFlag%3Dtrue&t=%3Cem%3E%E5%8D%95%E7%82%B9%E7%99%BB%E5%BD%95%3C%2Fem%3E
 **
 * @qualiFild pers.bc.utils.yonyou.NccSsoPartyAccess.java<br>
 * @author：LiBencheng<br>
 * @date Created on 2025年6月6日<br>
 * @version 1.0<br>
 */
public class NccSsoPartyAccess extends HttpServlet implements IHttpServletAdaptor
{
    /** @date 2025年6月5日 */
    private static final long serialVersionUID = 279866629713997857L;
    static String folderName = "ssoLogs";
    public static LoggerUtil logUtil = LoggerUtil.getInstance(folderName);
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        doAction(req, resp);
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        doAction(req, resp);
    }
    
    @Override
    public void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        try
        {
            exeLocalAccess(request, response);
            if (exeThirdPartyAccess(request, response)) //
                exeDoAction(request, response);
        }
        catch (Exception e)
        {
            JudgeAssertUtil.throwExceptionDir(e, folderName);
        }
    }
    
    /**
     * *********************************************************** <br>
     * *说明： <br>
     * @see <br>
     * @param request
     * @param response
     * @return <br>
     * @boolean <br>
     * @methods pers.bc.utils.yonyou.NccSsoPartyAccess#exeLocalAccess <br>
     * @author LiBencheng <br>
     * @date Created on 2025年6月9日 <br>
     * @time 下午7:02:45 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     * @throws Exception
     */
    protected void exeLocalAccess(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        String user = request.getParameter("usercode");
        JudgeAssertUtil.checkAssertDir(PubEnvUtil.isEmpty(user), folderName, "未传入用户信息, usercode为空！！！");
        // YonNccDB.bdUtil.getSuperByWhere(nc.vo.sm.UserVO.class, "nvl(dr, 0) = 0 AND user_code = '" + user +
        // "' and enablestate = 2 ", user);
        List<Map> list =
            YonNccDB.newUtil().getDataByWhere("sm_user", "nvl(dr, 0) = 0 AND user_code = '" + user + "' and enablestate = 2 ", user);
        JudgeAssertUtil.checkAssertDir(PubEnvUtil.getSize(list) < 1, folderName, "根据传入的用户编码【" + user + "】没有得到对应的用户信息！！");
        
    }
    
    /**
     * *********************************************************** <br>
     * *说明： 重寫此方法進行本地校驗d<br>
     * @see <br>
     * @throws Exception <br>
     * @void <br>
     * @methods pers.bc.utils.yonyou.NccSsoPartyAccess#exeLocalAccess <br>
     * @author LiBencheng <br>
     * @date Created on 2025年6月12日 <br>
     * @time 下午2:43:57 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    protected void exeLocalAccess(Map pram) throws Exception
    {
        String user = StringUtil.valueOfEmpty(pram.get("usercode"));
        JudgeAssertUtil.checkAssertDir(PubEnvUtil.isEmpty(user), folderName, "未传入用户信息, usercode为空！！！");
        // YonNccDB.bdUtil.getSuperByWhere(nc.vo.sm.UserVO.class, "nvl(dr, 0) = 0 AND user_code = '" + user +
        // "'
        // and enablestate = 2 ", user);
        List<Map> list =
            YonNccDB.newUtil().getDataByWhere("sm_user", "nvl(dr, 0) = 0 AND user_code = '" + user + "' and enablestate = 2 ", user);
        JudgeAssertUtil.checkAssertDir(PubEnvUtil.getSize(list) < 1, folderName, "根据传入的用户编码【" + user + "】没有得到对应的用户信息！！");
        
    }
    
    /**
     * *********************************************************** <br>
     * *说明： 第三方验证<br>
     * @see <br>
     * @param request
     * @param response
     * @return <br>
     * @boolean <br>
     * @methods pers.bc.utils.yonyou.ThirdPartyAccess#exeThirdPartyAccess <br>
     * @author LiBencheng <br>
     * @date Created on 2025年6月6日 <br>
     * @time 上午10:15:00 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    protected boolean exeThirdPartyAccess(HttpServletRequest request, HttpServletResponse response)
    {
        // 需要第三方验证，重新此方法
        return Boolean.TRUE;
    }
    
    /**
     * *********************************************************** <br>
     * *说明： 适用于NCC<br>
     * @see <br>
     * @param request
     * @param response
     * @throws Exception <br>
     * @void <br>
     * @methods pers.bc.utils.yonyou.NccSsoPartyAccess#exeDoAction <br>
     * @author LiBencheng <br>
     * @date Created on 2025年6月9日 <br>
     * @time 下午2:04:34 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    protected void exeDoAction(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        exeLocalAccess(CollectionUtil.newHashMap());
        // ThirdPartyLoginVerfiyAction 校驗token的
        // http://127.0.0.1:8888/uapws/service/ThirdPartyAccess?usercode=yy01
        String usercode = request.getParameter("usercode");
        String properPatch = getConfigPath();
        logUtil.info("从文件读取配置參數。。。。。properPatch：" + properPatch);
        Map<String, String> map = PropertiesUtil.getAllProperties(properPatch);
        // String baseurl = request.getScheme() + "://" + request.getServerName() + ":" +
        // request.getServerPort();
        String baseurl = request.getScheme() + "://" + request.getLocalAddr() + ":" + request.getLocalPort();
        if (PubEnvUtil.isNotEmptyObj(map.get("baseurl")))//
            baseurl = map.get("baseurl");
        String dsname = map.get("dsname");
        String busicentercode = map.get("busicentercode");
        String client_id = map.get("client_id");
        String client_security = map.get("client_security");
        logUtil.info("-----------单点获取token----------");
        String token = NCSSOUtil.genThirdPartyAccessToken(baseurl, dsname, usercode, busicentercode, client_id, client_security);
        // 单点成功后的跳转路径，这里为首页工作桌面
        String redirect_uri = baseurl + map.get("redirect_uri");
        // 单点登陆时的全路径，可以直接粘贴到浏览器进行访问。
        // redirect_uri "/fbip/resources/workbench/public/common/main/index.html#/";
        String fullUrl =
            baseurl + "/nccloud/resources/uap/rbac/thirdpartylogin/main/index.html?accesstoken=" + token + "&redirect_uri=" + redirect_uri;
        logUtil.info("获取的token为：" + token);
        logUtil.info("单点登陆全路径，复制到浏览器地址栏即可：" + fullUrl);
        
        response.sendRedirect(fullUrl);
        
    }
    
    public static void main(String[] args) throws Exception
    {
        String dsname = "design";// 数据源的编码，本地开发为design
        String usercode = "dcs";// 用户的编码
        String client_id = "TestThird";// 第三方系统id
        String client_security = "dee656e3c1";// 第三方秘钥
        String busicentercode = "develop";// 账套编码，本地开发时为develop
        String url = "http://127.0.0.1:8888/service/genThirdPartyAccessToken";
        String security = genKey(usercode, usercode + client_security + (System.currentTimeMillis() + "").substring(0, 6));
        String write = "type=type_security&dsname=" + dsname + "&usercode=" + usercode + "&client_id=" + client_id + "&security=" + security
            + "&busicentercode=" + busicentercode;
        write = write.replaceAll("\\+", "%2B");// 避免出现特殊符号问题。
        // 获取token
        String token = NCSSOUtil.getToken(url, write);
        if ("".equals(token))
        {
            System.out.println("获取token失败");
            return;
        }
        // 单点成功后的跳转路径，这里为首页工作桌面
        String redirect_uri = "http://127.0.0.1:8888/nccloud";
        // 单点登陆时的全路径，可以直接粘贴到浏览器进行访问。
        String fullUrl = "http://127.0.0.1:8888/nccloud/resources/uap/rbac/thirdpartylogin/main/index.html?accesstoken=" + token
            + "&redirect_uri=" + redirect_uri;
        System.out.println("获取的token为：" + token);
        System.out.println("单点登陆全路径，复制到浏览器地址栏即可：" + fullUrl);
        Logger.info("最终跳转的url:" + url);
        logUtil.info("最终跳转的url:" + url);
        
    }
    
    private static String genKey(String userid, String key) throws Exception
    {
        return new Base64().encodeToString(SignatureTookKit.digestSign(userid.getBytes(), key.getBytes()));
    }
    
    protected String getConfigPath()
    {
        StringBuffer sb = new StringBuffer();
        sb.append(RuntimeEnv.getInstance().getNCHome()).append(File.separator);
        sb.append("modules").append(File.separator);
        sb.append("baseapp").append(File.separator);
        sb.append("META-INF").append(File.separator);
        sb.append("websysteminfo.properties");
        
        return sb.toString();
    }
}
